const app = getApp();
Page({
	data: {
		url: app.globalData.host,
		list: {},
		theMonth: '',
		date: [],
		theDate: '',
		dateIndex: 0,
		timesList: [],
		timesInd: 0,
		attributeValueId: 0,
		theTime: '',
		price: '-',
		content: '',
		isKnew: false,
		canPay: false,
		isDisabled: false,

		isLoadBtn: false,	// 登录按钮

		code: null,
		token: null,
		infos: null,
	},
	onLoad: function (options) {
		this.setData({
			id: options.id
		})
		this.getData();
		this.getDate();
	},
	onShow() {
		this.getUserInfo();
	},
	// 从后台获取用户信息
	getUserInfo(){
		wx.showLoading({title: '加载中…'});
		app.request({
			url: '/app/user',
			method: 'GET',
			success: res => {
				if(res.code === 200){
					this.setData({
						list: [],
						isLoadBtn: false
					})
					this.getData();
					this.getDate();
				}else{
					this.setData({
						isLoadBtn: true
					})
				}
			}
		})
		wx.hideLoading();
	},
	// button 获取
	getPhoneNumber (e) {
		wx.login({
			success: info => {
				let iv = e.detail.iv;
				let code = info.code;
				let encryptedData = e.detail.encryptedData;
				let infos = {
					iv: e.detail.iv,
					code: info.code,
					encryptedData: e.detail.encryptedData
				}
				//手机号和验证码验证略
				let errMsg = e.detail.errMsg;
				if(errMsg == 'getPhoneNumber:ok'){
					this.setData({
						infos: infos
					})
					this.getPhone();
				}
			}
		})
	},
	getPhone(){
		if(this.data.inofs !== null && this.data.token !== null){
			let infos = this.data.infos
			app.request({
				url: '/app/binding',
				method: 'POST',
				data: infos,
				success: res => {
					if(res.code == 200){
						this.setData({
							[`userInfo.phone`]: res.data.phone
						})
						this.getUserInfo();
					}else{
						//弹出错误信息
						wx.showToast({
							title: res.data.msg,
							icon:'error'
						})
					}
				},
				fail: err => {
					console.log(err)
				}
			})
		}
	},
	getUserProfile(e) {
		let that = this;
		wx.login({
			success: code => {
				this.setData({
					code: code.code
				})
			}
		})
		wx.getUserProfile({
			desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: info => {
				this.setData({
					[`userInfo.avatar`]: info.userInfo.avatarUrl,
					[`userInfo.nickName`]: info.userInfo.nickName
				})
				wx.showLoading({title: '加载中…'});
				app.request({
					url: '/app/login',
					method: 'POST',
					data: {
						code: this.data.code,
						iv: info.iv,
						signature: info.signature,
						encryptedData: info.encryptedData,
					},
					success: res => {
						wx.setStorageSync('token',res.token);
						this.setData({
							token: res.token
						})
						this.getPhone();
					}
				})
				wx.hideLoading();
			}
		})
	},
	getData(){
		let id = this.data.id;
		app.request({
			url: '/app/project/' + id,
			method: 'GET',
			success: res => {
				let content = '';
				if(res.data.content){
					let contentInfo =  res.data.content.replace('<img ', '<img style="max-width:100%;height:auto;display:block;margin:10px 0;"')
					content = contentInfo.replace('src="/prod-api','src="' + this.data.url)
				}
				this.setData({
					list: res.data,
					content: content
				})

				wx.setNavigationBarTitle({
					title: res.data.projectName + " 预约"
				})
			}
		})
		wx.hideLoading();
	},

	// 获取可预约日期（单选日期）
	getDate(){
		let id = this.data.id;
		app.request({
			url: '/app/projectDate',
			method: 'GET',
			data:{
				projectId: id
			},
			success: res => {
				let list = res.data;
				let month = list[0].projectDate.split("-")[0] + '年' + list[0].projectDate.split("-")[1] + '月';
				this.setData({
					theMonth: month,
					theDate: list[0].projectDate
				})
				list.forEach((item,index) => {
					item.week = this.getWeekDate(item.projectDate);
					item.month = month;
					item.projectDay = item.projectDate.split("-")[2];
					item.projectMonth = item.projectDate.split("-")[0] + '-' + item.projectDate.split("-")[1];
					if(index == list.length - 1){
						this.setData({
							date: list
						})
					}
				})
				// 如果有可选时间段
				if(list[0].isInterval == 1){
					this.getTimes(list[0].projectDate);
				}else{
					// 没有时间段
				}
			}
		})
		wx.hideLoading();
	},
	// 获取星期几
	getWeekDate(date) {
		var now = new Date(date);
		var day = now.getDay();
		var weeks = new Array(
			"周日",
			"周一",
			"周二",
			"周三",
			"周四",
			"周五",
			"周六"
		);
		var week = weeks[day];
		return week;
    },
	// 根据日显示预约时段
	getDateAttr(e){
		let date = e.currentTarget.dataset.date;
		let index = e.currentTarget.dataset.index;
		let month = e.currentTarget.dataset.month;
		if(this.data.theMonth !== month){
			this.setData({
				theMonth: month
			})
		}
		this.setData({
			dateIndex: index,
			timesInd: 0,
			theDate: date
		})
		this.getTimes(date);
	},
	getTimes(date){
		let id = this.data.id;
		wx.showLoading({title: '加载中…'});
		app.request({
			url: '/app/projectDateValue',
			method: 'GET',
			data: {
				projectId: id,
				projectDate: date
			},
			success: res => {
				if(res.data){
					this.setData({
						theTime: res.data[0].attributeValue,
						price: res.data[0].price,
						attributeValueId: res.data[0].id,
						timesList: res.data
					})
				}
			}
		})
		wx.hideLoading();
	},
	checkTimeAttr(e){
		let index = e.currentTarget.dataset.index;
		let time = e.currentTarget.dataset.time;
		let price = Number(e.currentTarget.dataset.price);
		let id = e.currentTarget.dataset.id;
		this.setData({
			theTime: time,
			price: price,
			timesInd: index,
			attributeValueId: id
		})
	},

	changeKnew(){
		let isKnew = !this.data.isKnew;
		this.setData({
			isKnew: isKnew
		})
	},
	toSure(){
		let token = wx.getStorageSync("token");
		if(!token){
			wx.showToast({
				title: "请先登录",
				icon: 'none',//图标，支持"success"、"loading" 
				duration: 2000,//提示的延迟时间，单位毫秒，默认：1500 
				mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false 
				success:function(){},
				fail:function(){},
				complete:function(){}
			})
			setTimeout(()=>{
				wx.switchTab({
					url: '../../mine/mine'
				})
			},3000)
		}else{
			let id = this.data.id;
			if(!this.data.isDisabled){
				wx.showLoading({title: '加载中…'});
				app.request({
					url: '/app/order',
					method: 'POST',
					data: {
						projectId: id,
						attributeValueId: this.data.attributeValueId,
						// bookDate: this.data.theDate,
						// bookAttribute: this.data.theTime,
						price: this.data.price
					},
					success: res => {
						if(res.code == 200){
							wx.navigateTo({
								url: '../sure/sure?id=' + res.data
							})
						}else{
							wx.showToast({
								// title: "没有可预约时间段",
								title: res.msg,
								icon: 'none',//图标，支持"success"、"loading" 
								duration: 2000,//提示的延迟时间，单位毫秒，默认：1500 
								mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false 
								success:function(){},
								fail:function(){},
								complete:function(){}
							})
						}
					}
				})
				wx.hideLoading();
				this.setData({
					isDisabled: true
				})
				setTimeout(()=>{
					this.setData({
						isDisabled: false
					})
				},3000)
			}
		}
	},
	toAgreement(){
		wx.navigateTo({
			url: "../../mine/agreement/agreement"
		})
	},
})